package com.taofuxn.admin.api.service;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.collect.Maps;
import com.taofuxn.admin.api.model.SysUserModel;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author wong
 * @Date: 2020-05-06
 * @Version: 1.0
 */
@Service
public class SessionService {


    public final String USER_SESSION_KEY = "USER_SESSION_KEY";

    private Cache<String, SysUserModel> cache = CacheBuilder.newBuilder()
            .expireAfterAccess(1, TimeUnit.DAYS)
            .initialCapacity(0)
            .maximumSize(10000)
            .softValues()
            .build();

    private String getTokenKey(String token) {
        return "user:token:" + token;
    }

    public String addUserSession(SysUserModel sysUserModel) {
        if (null == sysUserModel)
            return null;
        String token = UUID.randomUUID().toString().replace("-", "");
        cache.put(getTokenKey(token), sysUserModel);
        return token;
    }

    public SysUserModel getUserSession(String token) {
        if (StringUtils.isEmpty(token))
            return null;
        return cache.getIfPresent(getTokenKey(token));
    }

    public void delUserSession(String token) {
        cache.invalidate(getTokenKey(token));
    }

    public boolean updateUserSession(String token, SysUserModel sysUserModel) {
        if (StringUtils.isEmpty(token)) {
            return false;
        }

        delUserSession(token);
        cache.put(getTokenKey(token), sysUserModel);

        return true;
    }

    public Map<String, SysUserModel> getAllUserToken() {
        return Maps.newHashMap(cache.asMap());
    }

    public boolean hasLogin(String token) {
        return getUserSession(token) != null;
    }


}
